package com.enlf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.enlf.dto.Result;
import com.enlf.dto.VoucherDTO;
import com.enlf.entity.Voucher;
import com.enlf.mapper.VoucherMapper;
import com.enlf.entity.SeckillVoucher;
import com.enlf.service.ISeckillVoucherService;
import com.enlf.service.IVoucherService;
import com.enlf.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author renge
 * @since 2023-9-11
 */
@Slf4j
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements IVoucherService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Result queryVoucherOfShop(Long shopId) {
        // 查询优惠券信息
        List<Voucher> vouchers = getBaseMapper().queryVoucherOfShop(shopId);
        List<VoucherDTO> voucherDTOList = vouchers.stream().map(voucher -> {
            VoucherDTO voucherDTO = BeanUtil.copyProperties(voucher, VoucherDTO.class);
            if (null != voucherDTO.getBeginTime()){
                voucherDTO.setBeginTime(voucher.getBeginTime().format(formatter));
                voucherDTO.setEndTime(voucher.getEndTime().format(formatter));
            }
            return voucherDTO;
        }).collect(Collectors.toList());
        log.debug(String.valueOf(voucherDTOList));
        // 返回结果
        return Result.ok(vouchers);
    }

    @Override
    @Transactional
    public void addSeckillVoucher(Voucher voucher) {
        // 保存优惠券
        save(voucher);
        // 保存秒杀信息
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);

        //将秒杀券信息存入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.SECKILL_STOCK_KEY+voucher.getId(),voucher.getStock().toString());
    }
}
